from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from django.contrib.auth.hashers import make_password,check_password
from .serializers import *
from django.core.paginator import Paginator
from django.db.models import Q,F
from datetime import datetime
import random
# 注册
class RegisterView(APIView):


    def post(self,request):
        username  = request.data.get('username')
        password  = request.data.get('password')
        pwd = make_password(password)
        data = {
            "username":username,
            "password":pwd
        }
        obj = RegisterSerializer(data=data)

        if obj.is_valid():
            obj.save()
            return Response({"code": 1000, "msg": "添加成功"})

        print(obj.errors)
        return Response({"code":1001,"msg":"缺少参数"})


# 登录
class LoginView(APIView):

    # 登陆日志  在什么时间 谁登录了此系统？

    def post(self,request):

        username = request.data.get('username')
        password = request.data.get('password')

        userobj = models.User.objects.filter(username=username).first()

        if not userobj:
            return Response({"code":1001,"msg":"用户名不存在"})

        pwd  =userobj.password


        if check_password(password,pwd):
            auth = userobj.auth
            uid = userobj.id
            return Response({"code":1000,"msg":"登录成功","data":{"auth":auth,"uid":uid}})
        return Response({"code":1000,"msg":"用户名或者密码错误"})


        pass


# 获取分类
class CategoryView(APIView):
    def get(self,request):
        # 获取分类的信息
        catequeryset = models.Category.objects.all()

        # 序列化
        obj = CateSerializer(catequeryset,many=True)


        # 返回
        return Response(obj.data)



# 商品
class GoodsView(APIView):

    # 查询
    def get(self,request):
        # 1 接收参数、数据
        p = request.GET.get("p",1)
        keyword = request.GET.get("keyword","").strip()

        # 2 查询所有的商品
        goodsqueryset = models.Goods.objects.filter(Q(name__contains=keyword)|Q(cate__name__contains=keyword)).all()

        # 3 分页
        page_obj = Paginator(goodsqueryset,per_page=2)

        # 4 获取分页的范围
        page = [i for i in page_obj.page_range]

        # 5 获取当前页的数据
        page_data = page_obj.page(p)

        # 6 判断上一页和下一页
        previous = page_data.has_previous()
        next = page_data.has_next()

        # 7 序列化当前页
        obj = GoodsSerializer(page_data,many=True)

        # 8 构造数据
        data = {
            "data":obj.data,
            "page":page,
            "previous":previous,
            "next":next
        }

        # 9 返回
        return Response({"code":1000,'msg':'','data':data})


    def post(self,request):
        #  1 接受数据
        name = request.POST.get('name')
        price = request.POST.get('price')
        cate = request.POST.get('cate')
        img = request.FILES.get('img')

        # 2 验证数据的重复性

        # 3 构造数据
        data = {
            "name":name,
            "price":price,
            "cate":cate,
            "img":img
        }
        # 4 反序列化
        obj = GoodsSerializer(data=data)
        # 5 判断
        if obj.is_valid():
            obj.save()
            return Response({"code": 1000, "msg": "添加成功"})
        # 6 打印信息
        print(obj.errors)
        # 7 返回值
        return Response({"code":1001,"msg":"参数有误"})



        pass



# 订单
class OrderView(APIView):

    # 查询订单
    def get(self,request):
        # 获取指定的人的id
        id = request.GET.get("uid")

        # 查询所有的订单
        orderqueryset = models.Order.objects.filter(user_id=id).all()

        # 序列化
        obj = OrderSerializer1(orderqueryset,many=True)

        # 返回
        return Response({"code":1000,"msg":"","data":obj.data})



        pass

    def generate_num(self):
        #　2020061914043025869
        return datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(10000,99999))

    # 添加
    def post(self,request):
        # 1 接收前端的数据
        uid = request.data.get("uid")
        goodid = request.data.get("goodid")
        num =  request.data.get("num")
        orderno = self.generate_num()

        # 2 茶订单的userid 和 goodid　是否存在？
        # 查询过滤单表的某个值的时候，只需要关注数据库的字段就可以了。
        orderobj = models.Order.objects.filter(user_id=uid,good_id=goodid).first()

        if orderobj:
            models.Order.objects.filter(user_id=uid, good_id=goodid).update(num=F('num')+num)
            return Response({"code":1000,"msg":"下单成功"})
        else:
            # 构造数据
            data = {
                "user":uid,
                "good":goodid,
                "orderno":orderno,
                "num":num
            }
            # 反序列化
            obj = OrderSerializer(data=data)
            # 判断
            if obj.is_valid():
                obj.save()
                return Response({"code":1000,"msg":"下单成功"})
            # 打印信息
            print(obj.errors)
            # 返回
            return Response({"code":1002,"msg":"参数有误"})
